<template>
  <div class="search_container">
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="0.48rem" class="goback" @click="$router.back()" />
      <!-- 搜索组件 -->
      <van-search placeholder="请输入搜索关键词" background="#007BFF" v-model="q" shape="round" v-focus
        @input="inputFn" @search="searchFn" />
    </div>
    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="this.q.length !== 0">
      <div class="sugg-item" v-for="item,index in suggestList" :key="index" v-html="lightFn(item, q)" @click="suggestClickFn(item)">
      </div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearHisFn"/>
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="item,index in history" :key="index" @click="historyClickFn(item)">{{ item }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getSuggestListAPI } from '@/api'

export default {
  name: 'MySearch',
  data () {
    return {
      q: '',
      timer: null,
      suggestList: [],
      history: JSON.parse(localStorage.getItem('history')) || [] // 搜索历史
    }
  },
  methods: {
    // 1.输入发生改变时监听
    inputFn () {
      clearTimeout(this.timer)
      // 防抖操作
      this.timer = setTimeout(async () => {
        if (this.q.length === 0) {
          this.suggestList = []
          return
        }
        const { data: res } = await getSuggestListAPI({ q: this.q })
        this.suggestList = res.data.options
      }, 500)
    },

    // 2.处理字符串用于高亮效果
    lightFn (originStr, target) {
      if (originStr === null) {
        return
      }
      const reg = new RegExp(target, 'ig')
      return originStr.replace(reg, match => {
        return `<span style="color: red">${match}</span>`
      })
    },

    // 3.输入框-搜索事件
    searchFn () {
      if (this.q.length > 0) {
        this.history.push(this.q)
        this.gotoSearchResultFn(this.q)
      }
    },

    // 4.点击联想词
    suggestClickFn (str) {
      this.history.push(str)
      this.gotoSearchResultFn(str)
    },

    // 5.点击搜索历史搜索词
    historyClickFn (str) {
      this.gotoSearchResultFn(str)
    },

    // 6.封装搜索跳转方法
    gotoSearchResultFn (str) {
      // 让宏任务先执行,再执行跳转
      setTimeout(() => {
        this.$router.push({
          path: `/search/${str}`
        })
      }, 0)
    },

    // 7.清空历史记录
    clearHisFn () {
      this.history = []
    }
  },
  watch: {
    history: {
      deep: true,
      handler () {
        const theSet = new Set(this.history)
        const arr = Array.from(theSet)
        localStorage.setItem('history', JSON.stringify(arr))
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;

  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }

  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}

/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
